<template>
  <div class="handle">
    <div class="title">
      <van-icon name="arrow-left" color="#ffffff" @click="skip_shop" />
      <van-col>购物车</van-col>
      <van-icon name="delete-o" color="#ffffff" @click="deleteGoods" />
    </div>
    <!-- 复选框和商品信息 -->
    <div class="center">
      <van-checkbox-group v-for="(item, index) in list" :key="index">
        <div class="collection">
          <!-- 复选按钮 -->
          <input
            type="checkbox"
            v-model="checkList"
            :value="item.id"
            class="checkbox"
            @change="computeTotal"
            :id="index"
          />
          <label :for="index" class="forCheckbox"
            ><van-icon name="success"
          /></label>
          <!-- 商品信息 -->
          <van-card
            :price="item.price"
            :desc="item.name"
            :thumb="item.showImg"
            id="money"
          />
        </div>
        <!-- 商品数量 -->
        <van-stepper v-model="item.number" @change="computeTotal" />
      </van-checkbox-group>
    </div>

    <!-- 优惠券单元格 -->
    <van-coupon-cell
      :coupons="coupons"
      :chosen-coupon="chosenCoupon"
      @click="showList = true"
    />
    <!-- 优惠券列表 -->
    <van-popup
      v-model="showList"
      round
      position="bottom"
      style="height: 90%; padding-top: 4px"
    >
      <van-coupon-list
        :coupons="coupons"
        :chosen-coupon="chosenCoupon"
        :disabled-coupons="disabledCoupons"
        @change="onChange"
        @exchange="onExchange"
      />
    </van-popup>

    <!-- 底部 -->
    <div class="bottom">
      <!-- 全选 -->
      <div class="Van-button">
        <!-- <van-button type="info" @click="toggleAll"></van-button> -->
        <input
          type="checkbox"
          class="checkbox"
          v-model="checked"
          @change="checkAll"
          id="whole"
        />
        <label for="whole" class="forCheckbox whole"
          ><van-icon name="success"
        /></label>
        <span>全部</span>
      </div>
      <div class="button-left">
        <ul>
          <li>合计：{{ totalPrice }} ￥</li>
          <li>&nbsp;已优惠 {{ discount }} ￥</li>
        </ul>
        <span @click="skip_confirm" class="settlement"
          >结算 ({{ totalNum }})</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import { getCart, getDeleteCart } from "../../../api/index";
import { Dialog } from "vant";
const coupon = {
  available: 1,
  condition: "无使用门槛\n最多优惠20元",
  reason: "",
  value: 2000,
  name: "通用券",
  startAt: 1489104000,
  endAt: 1514592000,
  valueDesc: "20",
  unitDesc: "元",
};
const coupon1 = {
  available: 2,
  condition: "无使用门槛\n最多优惠40元",
  reason: "",
  value: 4000,
  name: "通用券",
  startAt: 1489104000,
  endAt: 1514592000,
  valueDesc: "40",
  unitDesc: "元",
};
export default {
  data() {
    return {
      result: [],
      value: 1,
      list: [
        {
          name: "雅阁沙发",
          showImg: "https://img01.yzcdn.cn/vant/ipad.jpeg",
          price: "200",
          number: "2",
          id: 1,
        },
        {
          name: "落地台灯",
          showImg: "https://img01.yzcdn.cn/vant/ipad.jpeg",
          price: "100",
          number: "1",
          id: 2,
        },
      ],
      checkList: [],
      checked: false,
      totalPrice: "",
      totalNum: 0,
      chosenCoupon: -1,
      coupons: [coupon, coupon1],
      disabledCoupons: [coupon],
      showList: false,
      discount: 0,
      isDelete: false,
    };
  },
  methods: {
    checkAll() {
      var _this = this;
      if (!_this.checked) {
        //实现反选
        _this.checkList = [];
        // 全不选的情况
        this.totalNum = 0;
        this.totalPrice = 0;
        this.chosenCoupon = -1;
      } else {
        //实现全选
        _this.checkList = [];
        this.list.forEach(function (item, index) {
          _this.checkList.push(item.id);
        });
        // 全选后改变价格和商品数量
        this.totalNum = this.list.reduce((prev, cur) => {
          return prev + cur.number * 1;
        }, 0);
        this.totalPrice = this.list.reduce((prev, cur) => {
          return prev + cur.number * cur.price;
        }, 0);

        if (this.chosenCoupon !== -1) {
          this.totalPrice =
            this.totalPrice - this.coupons[this.chosenCoupon].value * 0.01;
        }
      }
    },
    // 总价格计算
    computeTotal() {
      // 每次点击商品选中框后计算价格
      this.totalNum = this.list.reduce((prev, cur) => {
        if (this.checkList.indexOf(cur.id) >= 0) {
          return prev + cur.number * 1;
        } else {
          return prev;
        }
      }, 0);
      this.totalPrice = this.list.reduce((prev, cur) => {
        if (this.checkList.indexOf(cur.id) >= 0) {
          return prev + cur.number * cur.price;
        } else {
          return prev;
        }
      }, 0);
      // 判断是否使用了优惠券
      if (this.chosenCoupon !== -1) {
        this.totalPrice =
          this.totalPrice - this.coupons[this.chosenCoupon].value * 0.01;
      }
    },
    skip_shop() {
      this.$router.push("/shop");
    },
    skip_confirm() {
      if (this.checkList.length > 0) {
        // 1、存储被选中商品信息, checkList中存储的是商品ID
        // console.log(this.checkList);
        let goods = [];
        this.list.map((item, index) => {
          if (this.checkList.indexOf(item.id) >= 0) {
            goods.push(item);
          }
        });
        let goodsData = {
          goods,
          price: this.totalPrice,
        };
        this.$store.commit("setGoodsList", goodsData);
        // 2、跳转到信息确认页
        this.$router.push("/confirm");
      } else {
        // 如果选中商品为空。
        // 无任何操作
      }
    },
    // 初始化购物车商品列表
    async initCart() {
      let userId = window.localStorage.getItem("user_id");
      let { data } = await getCart(userId);
      // console.log(data);
      this.list = data;
      this.list.forEach((item, index) => {
        if (!item.number) {
          item.number = 1;
        }
      });
    },
    onChange(index) {
      this.showList = false;
      this.chosenCoupon = index;
    },
    onExchange(code) {
      this.coupons.push(coupon);
    },
    deleteGoods() {
      // 判断是否有选中项
      if (this.checkList.length > 0) {
        Dialog.alert({
          message: "真的要将商品从购物车移出吗?",
          theme: "round-button",
        }).then(() => {
          this.isDelete = true;
        });
      }
    },
    // 删除购物车
    async deleteCart() {
        let obj = {
          uid: window.localStorage.getItem("user_id"),
        };
        this.list.map((item, index) => {
          if (this.checkList.indexOf(item.id) >= 0) {
            obj.gid = item.id;
          }
        });
        let res = await getDeleteCart(obj);
        // console.log(res.meta.status);
        if (res.meta.status == 200) {
          this.initCart();
        }
    },
  },
  created() {
    this.initCart();
  },
  watch: {
    checkList: {
      handler: function (val, oldVal) {
        if (val.length === this.list.length) {
          this.checked = true;
        } else {
          this.checked = false;
        }
        // 没有商品被选中时取消优惠券的选中
        if (val.length == 0) {
          this.chosenCoupon = -1;
        }
      },
      deep: true,
    },
    chosenCoupon: function (newVal, oldVal) {
      // 优惠券信息更新时重新计算商品总价
      if (newVal >= 0 && this.totalPrice >= 20) {
        if (oldVal !== -1) {
          this.totalPrice =
            this.totalPrice +
            this.coupons[oldVal].value * 0.01 -
            this.coupons[newVal].value * 0.01;
        } else {
          this.totalPrice = this.totalPrice - this.coupons[newVal].value * 0.01;
        }
        this.discount = this.coupons[newVal].value * 0.01;
      }
    },
    isDelete: function (newV, oldV) {
      if(newV) {
        this.deleteCart()
      }
    }
  },
};
</script>

<style lang="less" scoped>
.handle {
  width: 100%;
  background-color: #efefef;

  .title {
    height: 54px;
    background-color: #ff5555;
    padding: 0;
    padding-top: 16px;
    padding-bottom: 20px;
    display: flex;
    justify-content: space-between;
    .van-icon {
      padding: 10px 20px 0 16px;
      font-size: 42px;
    }
    .van-col {
      font-size: 18px;
      color: #ffffff;
      font-size: 34px;
      line-height: 54px;
    }
  }
  // 复选框和商品信息
  .center {
    min-height: 1104px;
    margin-bottom: 220px;
    .van-checkbox-group {
      height: 190px;
      display: flex;
      justify-content: space-between;
      background-color: #ffffff;
      margin: 20px;
      .collection {
        display: flex;

        // 商品
        .van-card {
          background-color: #ffffff;
          margin: 0;
          padding: 26px 0;

          .van-card__header {
            height: 138px;
            .van-card__thumb {
              width: 196px;
              height: 138px;
              margin-right: 20px;
            }

            .van-card__content {
              min-height: 138px;
              justify-content: center;
              align-items: center;
              .van-ellipsis {
                font-size: 24px;
                color: rgba(0, 0, 0, 0.8);
                margin-bottom: 20px;
              }
              .van-card__price-integer {
                font-size: 24px;
              }
            }
          }
        }
      }
      // 商品数量
      .van-stepper {
        margin-top: 100px;
        margin-right: 40px;
        /deep/ .van-stepper__minus,
        /deep/ .van-stepper__input,
        /deep/ .van-stepper__plus {
          background-color: #ffffff;
        }
        /deep/ .van-stepper__minus::before {
          background-color: #323232;
        }
      }
    }
  }

  .van-coupon-cell {
    position: fixed;
    bottom: 122px;
  }
  // 底部
  .bottom {
    height: 122px;
    width: 750px;
    background-color: #ffffff;
    display: flex;
    justify-content: space-between;
    position: fixed;
    bottom: 0;
    .Van-button {
      font-size: 22px;
      display: flex;
      padding-top: 46px;
      padding-left: 30px;

      input {
        width: 30px;
        height: 30px;
        margin-top: 2px;
      }
      .van-button::before {
        width: 30px;
        height: 30px;
      }
      span {
        margin-left: 5px;
        color: #ff5654;
      }
    }
    .button-left {
      display: flex;
      ul {
        font-size: 24px;
        padding-right: 30px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        li:nth-child(2) {
          color: #ff5654;
        }
      }
      span {
        width: 200px;
        background-color: #ff5654;
        color: #ffffff;
        text-align: center;
        line-height: 122px;
        font-size: 28px;
      }
    }
  }

  // 复选框
  .checkbox {
    display: none;
  }
  .forCheckbox {
    display: inline-block;
    width: 30px;
    height: 30px;
    border: 1px solid #ccc;
    margin: auto 20px;
    border-radius: 50%;
    // line-height: 30px;
    text-align: center;
    position: relative;
    .van-icon {
      font-size: 24px;
      color: #fff;
      position: absolute;
      bottom: 2px;
      left: 4px;
    }
  }
  .checkbox:checked + label {
    background-color: #ff5654;
    .van-icon {
      color: #fff;
    }
  }
  .whole {
    margin: 0;
    margin-right: 8px;
  }
}
</style>